package com.yfree.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.yfree.activities.YActivity;

import net.tsz.afinal.FinalActivity;

import java.lang.reflect.Field;

public abstract class YFragment extends Fragment {
    public View contentView;
    public boolean isLasy = false;
    private boolean yInited;

    public YActivity yActivity;
    public FragmentManager fragmentManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (contentView == null) {
            yActivity = (YActivity) getActivity();
            fragmentManager = getChildFragmentManager();
            contentView = yInflate(setContentViewId());
            contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    onYCreated();
                    contentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
            FinalActivity.initInjectedView(this, contentView);
        }
        ViewGroup parent = (ViewGroup) contentView.getParent();
        if (parent != null) {
            parent.removeView(contentView);
        }
        return contentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!isLasy) {
            loadViews();
        }
    }

    public void onYCreated() {
    }

    protected final void loadViews() {
        if (!yInited) {
            initViews();
            yInited = true;
        }
    }

    public View yInflate(int layoutId) {
        return getLayoutInflater().inflate(layoutId, null);
    }

    protected abstract int setContentViewId();

    protected abstract void initViews();

    @Override
    public void onLowMemory() {
        if (yActivity.yApplication != null)
            yActivity.yApplication.cleanMemory();
        super.onLowMemory();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (Exception ignored) {
        }
    }
}
